package com.anpy.security.interceptor;

import com.anpy.security.context.PlatformContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 平台拦截器
 * 用于从请求中提取平台代码并设置到上下文中
 */
@Component
public class PlatformInterceptor implements HandlerInterceptor {

    private static final String PLATFORM_HEADER = "X-Platform-Code";
    private static final String DEFAULT_PLATFORM = "default";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取平台代码
        String platformCode = request.getHeader(PLATFORM_HEADER);
        
        // 如果请求头中没有平台代码，使用默认值
        if (platformCode == null || platformCode.isEmpty()) {
            platformCode = DEFAULT_PLATFORM;
        }
        
        // 设置到上下文中
        PlatformContextHolder.setPlatformCode(platformCode);
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求完成后清除上下文
        PlatformContextHolder.clear();
    }
}
